package com.mask.im.server.push;


import com.mask.im.sdk.dto.IMPushMessage;
import com.mask.im.server.netty.enums.MaskIMPushMessageEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jian
 */
@Log4j2
@Component
public class IMPushMessageFactory {

    private final Map<MaskIMPushMessageEnum, IMAbstractPushMessage> processorCache = new ConcurrentHashMap<>();

    @Resource
    private ApplicationContext applicationContext;

    @PostConstruct
    public void initProcessors() {
        processorCache.put(MaskIMPushMessageEnum.FRIEND_MESSAGE,
                applicationContext.getBean(IMSingleMessageProcessor.class));
        processorCache.put(MaskIMPushMessageEnum.GROUP_MESSAGE,
                applicationContext.getBean(IMGroupMessageProcessor.class));
         processorCache.put(MaskIMPushMessageEnum.SYSTEM_MESSAGE,
                 applicationContext.getBean(IMSystemMessageProcessor.class));
        log.info("推送处理器初始化完成: {}", processorCache.keySet());
    }

    public IMAbstractPushMessage getProcessor(MaskIMPushMessageEnum messageEnum) {
        IMAbstractPushMessage processor = processorCache.get(messageEnum);
        if (processor == null) {
            log.warn("未找到对应的推送处理器: {}", messageEnum);
            throw new IllegalArgumentException("不支持的消息类型: " + messageEnum);
        }
        return processor;
    }

    public Boolean pushMessage(IMPushMessage<Object> message) {
        IMAbstractPushMessage processor = getProcessor(MaskIMPushMessageEnum.messageType(message.getPushType()));
        return processor.pushMessage(message);
    }
}
